const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

const users = new Set();

wss.on('connection', (ws) => {
    let username;
    ws.on('message', (message) => {
        const data = JSON.parse(message);
        if (data.type === 'login') {
            if (users.has(data.username)) {
                ws.send(JSON.stringify({
                    type: 'error',
                    message: 'Username already taken'
                }));
                ws.close();
                return;
            }
            username = data.username;
            users.add(data.username);
            broadcastUserList();
            broadcast({ 
                type: 'userJoined', 
                username: data.username 
            });
        } else if (data.type === 'message') {
            broadcast({
                type: 'message',
                username: data.username,
                message: data.message
            });
        }
    });

    ws.on('close', () => {
        users.forEach(user => {
            if (username === user) {
                users.delete(user);
                broadcastUserList();
                broadcast({
                    type: 'userLeft',
                    username: user
                });
            }
        });
    });
});

function broadcast(data) {
    wss.clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(JSON.stringify(data));
        }
    });
}

function broadcastUserList() {
    broadcast({
        type: 'userList',
        users: Array.from(users)
    });
}